package com.bootdo.system.service.impl;

import com.bootdo.common.utils.StringUtils;
import com.bootdo.system.dao.RecordDetailDao;
import com.bootdo.system.domain.RecordDetailDO;
import com.mchange.v2.beans.BeansUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.bootdo.system.dao.RecordDao;
import com.bootdo.system.domain.RecordDO;
import com.bootdo.system.service.RecordService;
import org.springframework.transaction.annotation.Transactional;


@Service
@Transactional
public class RecordServiceImpl implements RecordService {

	@Autowired
	private RecordDao recordDao;

	@Autowired
	private RecordDetailDao recordDetailDao;
	
	@Override
	public RecordDO get(Long id){
		return recordDao.get(id);
	}
	
	@Override
	public List<RecordDO> list(Map<String, Object> map){
		return recordDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return recordDao.count(map);
	}
	
	@Override
	public int save(RecordDO record){
		int count = 0;
		RecordDetailDO recordDetailDO = new RecordDetailDO();
		recordDetailDO.setVisitTime(new Date());
		recordDetailDO.setVisitIp(record.getVisitIp());
		recordDetailDO.setVisitAddress(record.getVisitAddress());
		if(StringUtils.isNotEmpty(record.getVisitPhone())) {
			//手机号访问
			record.setVisitType("1");
			recordDetailDO.setVisitPhone(record.getVisitPhone());
			//判断手机号是否已经访问
			RecordDO recordDO1 = recordDao.getRecordDetail(record);
			if(null == recordDO1) {
				//表示第一次添加
				record.setVisitCount(1l);
				record.setLastVisitTime(new Date());
				recordDao.save(record);
				recordDetailDO.setRecordId(record.getId());
			}else {
				//访问记录增加
				recordDetailDO.setRecordId(recordDO1.getId());
				recordDO1.setLastVisitTime(new Date());
				recordDao.addCount(recordDO1);
			}
		}else {
			//游客访问
			record.setVisitType("2");
			record.setVisitCount(1l);
			record.setLastVisitTime(new Date());
			recordDao.save(record);
			recordDetailDO.setRecordId(record.getId());
		}
		//新增记录详情表
		count = recordDetailDao.save(recordDetailDO);
		return count;
	}
	
	@Override
	public int update(RecordDO record){
		return recordDao.update(record);
	}
	
	@Override
	public int remove(Long id){
		return recordDao.remove(id);
	}
	
	@Override
	public int batchRemove(Long[] ids){
		return recordDao.batchRemove(ids);
	}
	
}
